﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DSheet.Core;
using DSheet.Core.Data;
using DSheet.DocLib;
using System.IO;
using System.Web.SessionState;

namespace DExcelServiceApp.Action
{
    /// <summary>
    /// GetDoc 的摘要说明
    /// </summary>
    public class GetDoc : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            string strDocId = context.Request.QueryString["docid"];
            string strTemplateId = context.Request.QueryString["templateid"];
            SessionData sdata = (context.Session["sd"] as SessionData);
            DContext dContext = new DContext();
            dContext.YearId = sdata.YearID;
            dContext.BDId = sdata.BDID;
            dContext.OrgId = sdata.ORGID;

            if (!string.IsNullOrEmpty(strTemplateId))
            {
                string filePath = null;
                Guid templateId = new Guid(strTemplateId);
                using (DBContext dbcontext = new DBContext())
                {
                    DocInstanceService instService = new DocInstanceService();
                    dContext.DBContext = dbcontext;
                    DocInstance docInst = instService.GetInstance(dbcontext, dContext.YearId, dContext.BDId, dContext.OrgId, templateId);
                    if (docInst == null)
                    {
                        DocTemplate docTemplate = new DocDefService().GetTemplate(dbcontext, templateId);
                        docInst = new DocInstance();
                        docInst.Id = Guid.NewGuid();
                        docInst.YearId = dContext.YearId;
                        docInst.BDId = dContext.BDId;
                        docInst.OrgId = dContext.OrgId;
                        docInst.TempalteId = templateId;
                        docInst.Name = docTemplate.Name;
                            
                        DocDef docDef = DocDefService.GetDocDef(dbcontext, docTemplate.DefId);

                        List<DocDim> pageDims = docDef.GetPageDims();
                        List<DRow> yRows = docDef.YDims.CalcDTree(dContext).Complanate();
                        List<DRow> xRows = docDef.XDims.CalcDTree(dContext).Complanate();

                        DocManager docManager = new DocManager();
                        filePath = docManager.CreateDoc(
                            docInst.Id,
                            @"c:\dsheet\docs\",
                            docInst,
                            docTemplate.Serialize(docDef.YDims, docDef.XDims, pageDims), 
                            docTemplate.SerializeY(yRows), 
                            docTemplate.SerializeX(xRows));

                        docInst.Name = docDef.Name;
                        docInst.FilePath = filePath;
                        instService.CreateInstance(dbcontext, docInst);
                    }
                    else
                    {
                        filePath = docInst.FilePath;
                    }
                }
                FileInfo fileInfo = new FileInfo(filePath);
                context.Response.Clear();
                context.Response.ClearContent();
                context.Response.ClearHeaders();
                context.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name);
                context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                context.Response.AddHeader("Content-Transfer-Encoding", "binary");
                context.Response.ContentType = "application/octet-stream";
                context.Response.WriteFile(filePath);
            }
            else if (!string.IsNullOrEmpty(strDocId))
            {
                Guid docId = new Guid(strDocId);
                string filePath = null;
                using (DBContext dbcontext = new DBContext())
                {
                    DocInstanceService instService = new DocInstanceService();
                    dContext.DBContext = dbcontext;

                    DocInstance docInst = instService.GetInstance(dbcontext, docId);
                    filePath = docInst.FilePath;
                }
                FileInfo fileInfo = new FileInfo(filePath);
                context.Response.Clear();
                context.Response.ClearContent();
                context.Response.ClearHeaders();
                context.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name);
                context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                context.Response.AddHeader("Content-Transfer-Encoding", "binary");
                context.Response.ContentType = "application/octet-stream";
                context.Response.WriteFile(filePath);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}